<html>
<head>
  <link href="node_modules/mocha/mocha.css" rel="stylesheet">
  <script type="text/javascript" src="zepto.min.js"></script>
  <script type="text/javascript" charset="utf-8">
    // Remove symbols of node-webkit to avoid conficts with mocha in browser.
    var nodeRequire = require;
    var nodeGlobal = global;
    var nodeProcess = process;
    require = undefined;
    global = undefined;
    process = undefined;
  </script>
  <!--
  Use the browser version of mocha, the node version of mocha will
  run tests in node contex, which make it imposssible to test nw.gui.
  -->
  <script type="text/javascript" src="node_modules/mocha/mocha.js"></script>
  <script type="text/javascript" charset="utf-8">
    // Restore default node-webkit environment.
    require = nodeRequire;
    global = nodeGlobal;
    process = nodeProcess;
  </script>
</head>
<body>

<div id="mocha"></div>

<script type="text/javascript" charset="utf-8">
  var fs = require('fs');
  var gui = require('nw.gui');
  var path = require('path');
  var program = require('commander');
  global.local_server = require('./server/server');
  var local_server = global.local_server;
  var list = new Array();
  //socket server
  var net = require('net');
  global.server = net.createServer();
  var server = global.server;
  // TODO
  // 1) Make user choose which test to run in command line.
  // 2) Add option to print results to file.

  // Hook process.exit to App.quit.
  process.exit = function() {
    server.close();
    gui.App.quit();
  }

  // Parse command line arguments.
  program
    .version(JSON.parse(fs.readFileSync('package.json', 'utf8')).version)
    .option('-S, --silent', 'hide the browser window (run silently)')
    .option('-o, --output <name>', 'output the results to specifed file, usually used together with json reporter')
    .option('-R, --reporter <name>', 'specify the reporter to use', 'html')
    .option('-g, --grep <pattern>', 'only run tests matching <pattern>')
    .option('-i, --invert', 'inverts --grep matches')
    .option('-t, --timeout <ms>', 'set test-case timeout in milliseconds [2000]')
    .option('-s, --slow <ms>', '"slow" test threshold in milliseconds [75]')
    .option('-b, --bail', "bail after first test failure")
    .option('-A, --async-only', "force all tests to take a callback (async)")
    .option('-p, --port <port>', "set the port used by socket")
    .option('-v, --verbose', "show the test case which is running.")
    .option('-l, --list', "list all test cases")
    .parse([ 'node-webkit', 'nw-test' ].concat(gui.App.argv));

  // --silent
  if (!program.silent) gui.Window.get().show();
  // --grep
  if (program.grep) mocha.grep(new RegExp(program.grep));
  // --invert
  if (program.invert) mocha.invert();
  // --slow <ms>
  if (program.slow) mocha.suite.slow(program.slow);
  // --timeout
  if (program.timeout) mocha.suite.timeout(program.timeout);
  // --bail
  mocha.suite.bail(program.bail);
  // --async-only
  if (program.asyncOnly) mocha.asyncOnly();
  // --reporter <name>
  if (program.reporter == 'json')
    mocha.reporter(require('./json_reporter.js'));
  else
    mocha.reporter(program.reporter);
  // --output <name>
  if (program.output)
    process.stdout.write = function(data) {
      fs.writeFileSync(program.output, data, 'utf8');
    }

  // --verbose
  if (program.verbose) global.verbose = true;
  global.auto = true;

  global.port = 13013;
  if (program.port) global.port = program.port;


  // Call this to set 'describe', 'it' and else.
  mocha.setup('bdd');
  global.tests_dir = 'automatic_tests';
  // Read all test files.
  var dirs = fs.readdirSync(global.tests_dir);
  for (var i = 0; i < dirs.length;i++){
    var test_file_path = path.join(global.tests_dir, dirs[i], 'mocha_test.js');

    if (fs.existsSync(test_file_path)){
      var content = fs.readFileSync(test_file_path);
      // Get all the test cases
      var content_tmp = content + "", content_bet, n, n1 = 0, obj, obj1;
      obj1 = new Object();
      obj1.depth = 1;		      
      
      while (program.list && content_tmp.length != 0) {  
          n = content_tmp.search('describe');
	  if (n == -1)
	      break;
	  n1 = content_tmp.search('{');
          content_bet = (content_tmp + "").slice(n1, n);
          var c = content_bet.split('{').length - content_bet.split('}').length;

          content_tmp = content_tmp.slice(n);
          n1 = content_tmp.search('{');
	  n1 = content_tmp.lastIndexOf(',' ,n1);
          obj = new Object();                 
          obj.test_name = content_tmp.slice(10, n1 - 1);
          content_tmp = content_tmp.slice(n1);
          obj.depth = obj1.depth + c;
	 
	  list.push(obj);
          obj1 = obj;
      }
      
	
      // Simple wrapped 'eval' to setup tests, so:
      // 1) working directory is the directory of 'index.html'.
      // 2) tests run in window context.
      // 3) global variables in each test are wrapped in its local scope.
      // 4) tests are setup synchronously.
      try {
        eval('(function() {' + content + '})();');
      } catch (e) {
        console.log(e);
      }
    }
  }

  if (program.list) {
      for (var i = 0; i < list.length; i++) {
	  var split = '-';
	  process.stdout.write(new Array(list[i].depth).join(split) + list[i].test_name + '\n');
      }
      process.stdout.write("Report total: " + list.length + '\n');
      server.close = function(){}
      server.listen = function() {}
      process.exit();
  }



  server.on('listening', function(){
    // Run!
    if (program.silent)
      mocha.run(gui.App.quit);
    else
      mocha.run();
  });

  server.on('error', function(e){
    if (e.code == 'EADDRINUSE'){
      console.log('Port in use, retrying new..');
      server.close();
      global.port += 1;
      server.listen(global.port);
    }
  });

  server.listen(global.port);




</script>
</body>
</html>
